package com.zline.foodraise.ui.activity;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.zline.foodraise.R;
import com.zline.foodraise.adapter.TradingListAdapter;
import com.zline.foodraise.constant.Constant;
import com.zline.foodraise.entity.TradingBean;
import com.zline.foodraise.http.HttpDataParsing;
import com.zline.foodraise.http.HttpErro;
import com.zline.foodraise.http.HttpOperator;
import com.zline.foodraise.http.HttpUtil;
import com.zline.foodraise.listener.RecyclerOnScrollListener;
import com.zline.foodraise.util.LUtil;
import com.zline.foodraise.util.NetworkUtil;
import com.zline.foodraise.util.TUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by heshantao on 15/11/12.
 * 交易明细
 */
@EActivity(R.layout.activity_trading_detail)
public class TradingDetailActivity extends ZlineActivity {
    private static final String LOG_TAG = TradingDetailActivity.class.getSimpleName();
    @StringRes(R.string.trading_detail)
    String title;
    @ViewById(R.id.app_common_header_title_tv)
    TextView title_tv;
    @ViewById(R.id.trading_list_recyclerView)
    RecyclerView trading_recyclerView;
    @ViewById(R.id.trading_list_srl)
    SwipeRefreshLayout swipeRefreshLayout;
    SparseArray<TradingBean> sparseArray;
    //账户类别1、筹红包；2、账户余额
    @Extra
    int type;
    @Bean
    HttpUtil httpUtil;
    @Bean
    HttpOperator httpOperator;
    int resultCode = 0;
    @Bean
    HttpErro httpErro;
    //当前页
    int currt_page = 1;
    //共多少页
    int pageCount;
    @Bean
    HttpDataParsing httpDataParsing;
    LinearLayoutManager layoutManager;
    @Bean
    TradingListAdapter tradingListAdapter;
    @ViewById(R.id.exception_fl)
    FrameLayout exception_fl;
    @ViewById(R.id.exception_rl)
    RelativeLayout exception_rl;
    @ViewById(R.id.ex_no_data_rl)
    RelativeLayout no_data_rl;
    @Bean
    NetworkUtil networkUtil;
    //是否加载失败
    boolean loadFail = false;
    //第一次加载数据
    boolean firstLoad = true;
    //加载更多
    boolean loadMore = false;

    @AfterViews
    void doSomeAfterViews() {
        sparseArray = new SparseArray<TradingBean>();
        initView();
        requestData();
    }


    void initView() {
        title_tv.setText(title);
        initRecyclerView();
        initSwipRefreshLayout();
    }

    //请求数据
    void requestData() {
        if (networkUtil.isNetworkAvailable()) {
            showLoadingDialog();
            requestTradingList();
        } else {
            showLoadFailView(true);
            TUtil.showShort(TradingDetailActivity.this, R.string.no_network);
        }
    }

    //是否加载失败显示重新加载页面
    void showLoadFailView(boolean isException) {
        loadFail = isException;
        if (isException) {
            exception_fl.setVisibility(View.VISIBLE);
            exception_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            exception_rl.setVisibility(View.GONE);
        }
    }

    //是否显示暂无数据
    void showNoDataView(boolean noData) {
        if (noData) {
            exception_fl.setVisibility(View.VISIBLE);
            no_data_rl.setVisibility(View.VISIBLE);
        } else {
            exception_fl.setVisibility(View.GONE);
            no_data_rl.setVisibility(View.GONE);
        }
    }

    //初始化RecyclerView
    void initRecyclerView() {
        trading_recyclerView.setItemAnimator(new DefaultItemAnimator());
        trading_recyclerView.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        trading_recyclerView.setLayoutManager(layoutManager);
        tradingListAdapter.setAdapterData(sparseArray);
        trading_recyclerView.setAdapter(tradingListAdapter);
        trading_recyclerView.addOnScrollListener(new RecyclerOnScrollListener(layoutManager) {
            @Override
            public void onLoadMore() {
                if (currt_page < pageCount) {
                    if (networkUtil.isNetworkAvailable()) {
                        currt_page++;
                        loadMore = true;
                        showRecyclerFoot(true);
                        requestTradingList();
                    } else {
                        TUtil.showShort(TradingDetailActivity.this, R.string.no_network);
                    }
                }

            }
        });
    }


    //初始化SwipRefreshLayout
    void initSwipRefreshLayout() {
        //设置加载颜色
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light, android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (networkUtil.isNetworkAvailable()) {
                    currt_page = 1;
                    requestTradingList();
                } else {
                    stopRefresh();
                    TUtil.showShort(TradingDetailActivity.this, R.string.no_network);
                }

            }
        });
    }


    //请求交易明细列表
    void requestTradingList() {
        httpOperator.requestTradingDetailList(httpUtil,type,
                Constant.PAGE_ROWS_NUMBER, currt_page, requestTradingListHandler);
    }


    //获取交易明细列表回调
    AsyncHttpResponseHandler requestTradingListHandler = new JsonHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
            super.onSuccess(statusCode, headers, response);
            LUtil.i(LOG_TAG, "____successs_____requestTradingListHandler_____" + statusCode + response.toString());
            if (statusCode == 200) {
                try {
                    resultCode = response.getInt(Constant.RESULT_CODE);
                    if (resultCode == 200) {//调用成功
                        sparseArray = httpDataParsing.getTradingInfo(response);
                        getPageCount(response);
                        if (swipeRefreshLayout.isRefreshing()) {
                            refreshData(sparseArray);
                        } else {
                            loadMoreData(sparseArray);
                        }
                    } else {
                        loadFailInfo();
                        if (firstLoad) {
                            showLoadFailView(true);
                        } else {
                            httpErro.showCommonErroResult(resultCode);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                } finally {
                    firstLoad = false;
                    dissLoadingDialog();
                }
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            super.onFailure(statusCode, headers, responseString, throwable);
            loadFailInfo();
            dissLoadingDialog();
            if (firstLoad) {
                showLoadFailView(true);
            }

        }
    };

    //刷新数据
    void refreshData(SparseArray<TradingBean> tradingArray) {
        if (loadFail) {
            showLoadFailView(false);
        }
        tradingListAdapter.setAdapterData(tradingArray);
        tradingListAdapter.notifyDataSetChanged();
        stopRefresh();
        isNoDataException();
    }

    //加载更多数据
    void loadMoreData(SparseArray<TradingBean> tradingArray) {
        loadMore = false;
        if (currt_page == pageCount) {
            showRecyclerFoot(false);
        }
        if (loadFail) {
            showLoadFailView(false);
        }
        tradingListAdapter.addAll(tradingArray);
        if (currt_page == 1) {
            isNoDataException();
        }
    }

    //是否显示暂时没有数据
    void isNoDataException() {
        int size = tradingListAdapter.getArrys().size();
        if (size == 0) {
            showNoDataView(true);
        } else {
            showNoDataView(false);
        }
    }

    //是否显示正在加载
    void showRecyclerFoot(boolean bol) {
        if (tradingListAdapter != null) {
            tradingListAdapter.setFootEnable(bol);
            tradingListAdapter.notifyItemChanged(tradingListAdapter.getArrys().size());
        }
    }

    //加载失败时候情况处理
    void loadFailInfo() {
        stopRefresh();
        if (loadMore) {
            currt_page--;
        }
        if (tradingListAdapter.getFootEnable()) {
            showRecyclerFoot(false);
        }
        firstLoad = false;
    }


    //停止刷新
    void stopRefresh() {
        if (swipeRefreshLayout.isRefreshing()) {
            swipeRefreshLayout.setRefreshing(false);
        }
    }

    //分页查找共多少页
    @Background
    void getPageCount(JSONObject json) {
        try {
            JSONObject jsonObject = json.getJSONObject(Constant.USER_ACCOUNT_DETAIL_PAGE);
            pageCount = jsonObject.getInt(Constant.PAGE_COUNT);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Click({R.id.app_common_header_left_icon_iv, R.id.reload_tv})
    void onClick(View view) {
        switch (view.getId()) {
            case R.id.app_common_header_left_icon_iv:
                goback();
                break;
            case R.id.reload_tv:
                requestData();
                break;
            default:
                break;
        }
    }

}
